<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="行程标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入行程标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:travelItinerary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:travelItinerary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:travelItinerary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:travelItinerary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="travelItineraryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="行程标题" align="center" prop="title" />
      <el-table-column label="行程开始日期" align="center" prop="startDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="行程结束日期" align="center" prop="endDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人数" align="center" prop="personNum" />
      <el-table-column label="联系人" align="center" prop="contactPerson" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="客户单位" align="center" prop="cust" />
      <el-table-column label="行程描述" align="center" prop="description" width="220" />
      <!-- <el-table-column label="类型" align="center" prop="travelType" />
      <el-table-column label="状态" align="center" prop="status" /> -->
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:travelItinerary:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:travelItinerary:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改行程管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1300px" append-to-body>
      <el-form ref="budgetRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择行程" prop="id" >
          <el-select v-model="form.id" placeholder="请选择行程标题" :disabled="isEdit"
            @change="handleTravelTitleChange">
            <el-option
              v-for="item in travelList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-row >
          <el-col :span="6">
            <el-divider content-position="center">行程信息</el-divider>
            <div v-if="form.id">
              <el-form-item label="行程">
                <el-text type="primary">{{form.title}}</el-text>
              </el-form-item>
              <el-form-item label="日期">
                <el-text type="primary">{{form.startDate}} — {{form.endDate}}</el-text>
              </el-form-item>
              <el-form-item label="人数">
                <el-text type="primary">{{ form.personNum }}</el-text>
              </el-form-item>
              <el-form-item label="联系人">
                <el-text type="primary">{{ form.contactPerson}}({{ form.contactPhone }})</el-text>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="17" :offset="1" >
            <el-divider content-position="center">预算</el-divider>
            <div v-if="form.id">
              <el-row :gutter="10" class="mb8" >
                <el-col :span="1.5">
                  <el-button type="primary" icon="Plus" @click="handleAddBudget">添加</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="danger" icon="Delete" @click="handleDeleteBudget">删除</el-button>
                </el-col>
              </el-row>
              <el-table :data="budgetList" :row-class-name="rowBudgetIndex" @selection-change="handleBudgetSelectionChange" ref="budget" width="800">
                <el-table-column type="selection" width="50" align="center" />
                <!-- <el-table-column label="序号" align="center" prop="index" width="50"/> -->
                
                <el-table-column label="地点" prop="spotName" width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.spotName" placeholder="请输入地点"/>
                  </template>
                </el-table-column>
                <el-table-column label="费用名称" prop="feeName" width="180">
                  <template #default="scope">
                    <el-input v-model="scope.row.feeName" placeholder="费用名称"/>
                  </template>
                </el-table-column>
                <el-table-column label="收费方式" prop="feeType" width="130" >
                  <template #default="scope">
                    <el-select v-model="scope.row.feeType" @change="handleFeeTypeChange(scope.row)">
                      <el-option
                        v-for="dict in fee_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="parseInt(dict.value)"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="单价" prop="feePrice" width="80">
                  <template #default="scope">
                    <el-input v-model="scope.row.feePrice" placeholder="费用名称"/>
                  </template>
                </el-table-column>
                <el-table-column label="数量" prop="quantity" width="80">
                  <template #default="scope">
                    <el-input v-model="scope.row.quantity" placeholder="费用名称"/>
                  </template>
                </el-table-column>
                <el-table-column label="总价" prop="totalAmount" width="120">
                  <template #default="scope">
                    <el-input 
                      v-model="scope.row.totalAmount" 
                      placeholder="费用名称"
                      @click="calculateTotal(scope.row)" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
  
        
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TravelItinerary">
import { getTravelBudget,listTravelItinerary,listTravelItineraryBudget, getBudget, updateTravelItinerary } from "@/api/manage/travelItinerary";
import { batchAddBudget,delBudgetByItineraryId } from "@/api/manage/budget";
import {listSpot}  from '@/api/manage/spot'
import {loadAllParams}  from '@/api/page'

const { proxy } = getCurrentInstance();
const { fee_type } = proxy.useDict('fee_type');

const travelItineraryList = ref([]);
const budgetList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedBudget = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isEdit = ref(false); // 是否为编辑状态






const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    travelType: null,
    status: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询行程管理列表 */
function getList() {
  loading.value = true;
  listTravelItineraryBudget(queryParams.value).then(response => {
    travelItineraryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    personNum: null,
    contactPerson: null,
    contactPhone: null,
  };
  budgetList.value = [];
  proxy.resetForm("budgetRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  isEdit.value = false;
  reset();
  open.value = true;
  title.value = "添加行程预算";  
}

/** 修改按钮操作 */
function handleUpdate(row) {
  isEdit.value = true;
  reset();
  const _id = row.id || ids.value
  getBudget(_id).then(response => {
    form.value = response.data;
    budgetList.value = response.data.budgetList;
    handleBudgetList();
    open.value = true;
    title.value = "修改行程管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["budgetRef"].validate(valid => {
    if (valid) {
      if (budgetList && Array.isArray(budgetList.value)) {
        for (let index = 0; index < budgetList.value.length; index++) {
          const element = { ...budgetList.value[index] }; // 创建副本保证响应性
          element.title = form.value.title;
          element.itineraryId = form.value.id;
          element.personNum = form.value.personNum; // 加可选链防止访问未定义属性
          budgetList.value[index] = element;
        }
      }
      form.value.budgetList = budgetList.value;
      // 给每一项添加title
      
      if (isEdit.value) {
        delBudgetByItineraryId(form.value.id).then(response => {
          if (response.code === 200) {
              batchAddBudget(form.value.budgetList).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            })
          }  
        })
      } else {
          batchAddBudget(form.value.budgetList).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除行程管理编号为"' + _ids + '"的数据项？').then(function() {
    return delBudgetByItineraryId(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 每日行程序号 */
function rowBudgetIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 每日行程添加按钮操作 */
function handleAddBudget() {
  let obj = {};
  obj.spotName = "";
  obj.feeName = "";
  obj.feeType = "";
  obj.feePrice = "";
  obj.quantity = "";
  obj.totalAmount = "";
  budgetList.value.push(obj);
}

/** 每日行程删除按钮操作 */
function handleDeleteBudget() {
  if (checkedBudget.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的每日行程数据");
  } else {
    const budgets = budgetList.value;
    const checkedBudgets = checkedBudget.value;
    budgetList.value = budgets.filter(function(item) {
      return checkedBudgets.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleBudgetSelectionChange(selection) {
  checkedBudget.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/travelItinerary/export', {
    ...queryParams.value
  }, `travelItinerary_${new Date().getTime()}.xlsx`)
}


/** 处理地点选择 */

function handleFeeTypeChange(row) {
  console.log(row.feeType);

  if (row.feeType == 1) {
    row.quantity = row.personNum;
  }
  else{
    row.quantity = 1;
  }
}

/** 处理行程标题选择 */
const handleTravelTitleChange = (value) => {
  
  let traveInfo = travelList.value.find(item => item.id === value);
  form.value.id = traveInfo.id;
  form.value.startDate = traveInfo.startDate;
  form.value.endDate = traveInfo.endDate;
  form.value.personNum = traveInfo.personNum;
  form.value.title = traveInfo.title;
  form.value.contactPerson = traveInfo.contactPerson;
  form.value.contactPhone = traveInfo.contactPhone;
  getTravelBudgetAll(value);
  console.log(form.value);
}


/** 查询所有预算 */
function getTravelBudgetAll(id){
  getTravelBudget(id).then(response => {
    budgetList.value = response.data;
    handleBudgetList();
  });
}

/** 处理buggetList */
const handleBudgetList = () => {
  budgetList.value.forEach(item => {
    //判断quantity是否为空
    if (item.quantity == null || item.quantity == undefined || item.quantity == '') {
      if (item.feeType == 1) {
        item.quantity = item.personNum;
      }
      if (item.feeType == 2) {
        item.quantity = 1;
      }
    }
    //判断totalAmount是否为空
    if (item.totalAmount == null || item.totalAmount == undefined || item.totalAmount == '') {
      item.totalAmount = (item.feePrice * item.quantity).toFixed(2); // 保留两位小数
    }
  });
}

/** 计算总价 */
function calculateTotal(row) {
  const price = parseFloat(row.feePrice) || 0;
  const quantity = parseInt(row.quantity) || 0;
  row.totalAmount = (price * quantity).toFixed(2); // 保留两位小数
}

/** 查询所有行程   */
const travelList = ref([]);
function getTravelItineraryAllList(){
  listTravelItinerary(loadAllParams).then(response => {
    travelList.value = response.rows;
  });
}
/** 查询所有景点 */

const spotList = ref([]);
function getSpotList(){
  listSpot(loadAllParams).then(response => {
    spotList.value = response.rows;
  });
}
getTravelItineraryAllList();
getSpotList();
getList();

</script>
